package lanbo.cj.lmp.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.nfc.*;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.*;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.*;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import lanbo.cj.lmp.BaseApplication;
import lanbo.cj.lmp.Config;
import lanbo.cj.lmp.R;
import lanbo.cj.lmp.bean.*;
import lanbo.cj.lmp.utils.LocalData;
import lanbo.cj.lmp.utils.NetChangeBroad;
import lanbo.cj.lmp.view.DialogTips;
import lanbo.cj.lmp.view.RoundImageView;
import zxing.activity.CaptureActivity;

import java.io.Serializable;
import java.util.*;

public class MainActivity extends Activity {
    private static int Reqeusted_QR = 0;
    private boolean isKeshi;
    private boolean isStartService;//点击开发服务，选择手术类型后变成true,否则变成false
    private ImageView setting,iv_qr;
    private TextView mName, mType, mState, mBirth, mDate, mManu, mServiceText, mKeShi, mOperaTion, mCardText;
    private RoundImageView mService;
    private boolean isStart;
    private String assertName, currentAssetId, currentKeshiName, currentOperation;
    private int currentKeshi;
    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
    private Record mRecord;
    public static String FILENAME = "fileName";
    private int currentKeshiId = 0;
    LinearLayout layout_all;
    PopupWindow avatorPop;
    private Map<String, Object> currentMap;//当前界面上显示的Map
    private int currentAssetState;
    private RelativeLayout card1, card2, card3, card4;
    private DialogTips writekeshiDialog, startOperaDialog;
    private int cancelKel;//0为绑定，1为解除
    private NetChangeBroad netChangeBroad = new NetChangeBroad();
    private AlertDialog setKeshiDialog;
    private String[] keshiIteams = {"无科室", "神经科", "心脏科", "口腔科"};

    private int keshiItemOption = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        if (!checkHasNfc()) return;//如果没有nfc模块,跳出对话框
        BaseApplication mBaseApplication = (BaseApplication) getApplication();
        mBaseApplication.mLocationClient.start();
        findviewBy();
        setListener();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netChangeBroad, intentFilter);


    }

    private void findviewBy() {
        currentAssetState = Config.STATE_NOT_USE;
        currentMap = null;
        setting = (ImageView) findViewById(R.id.setting);
        iv_qr = (ImageView)findViewById(R.id.iv_qr);
        mService = (RoundImageView) findViewById(R.id.service);
        isStart = false;
        isStartService = false;
        isKeshi = false;
        mName = (TextView) findViewById(R.id.tag_name);
        mType = (TextView) findViewById(R.id.tag_type);
        mState = (TextView) findViewById(R.id.tag_state);
        mBirth = (TextView) findViewById(R.id.tag_birth);
        mDate = (TextView) findViewById(R.id.tag_date);
        mManu = (TextView) findViewById(R.id.tag_manu);
        mKeShi = (TextView) findViewById(R.id.tag_keshi);
        mOperaTion = (TextView) findViewById(R.id.tag_recOpera);
        mServiceText = (TextView) findViewById(R.id.tv_service);
        mCardText = (TextView) findViewById(R.id.card3Tv);
        card1 = (RelativeLayout) findViewById(R.id.card1);
        card2 = (RelativeLayout) findViewById(R.id.card2);
        card3 = (RelativeLayout) findViewById(R.id.card3);
        card4 = (RelativeLayout) findViewById(R.id.card4);


        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        ndef.addCategory("*/*");
        mFilters = new IntentFilter[]{ndef};// 过滤器
        mTechLists = new String[][]{new String[]{MifareClassic.class.getName()},
                new String[]{NfcA.class.getName()}};// 允许扫描的标签类型

    }
    // 获取nfc适配器，判断设备是否支持NFC功能
    private boolean checkHasNfc(){

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            DialogTips noNfcDialog = new DialogTips(MainActivity.this, "该机型不支持nfc\n请更换手机", "确认退出");
            noNfcDialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                    return;
                }
            });
            noNfcDialog.show();
            return false;
        }
        if (!nfcAdapter.isEnabled()) {
            Toast.makeText(MainActivity.this, "nfc功能未打开，请打开nfc", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

    private void setListener() {
        setting.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Intent i = new Intent();
                i.setClass(MainActivity.this, SettingActivity.class);
                startActivity(i);
            }
        });
        iv_qr.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(i,Reqeusted_QR);
            }
        });
        mService.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                if (isStart) {
                    if (currentKeshiId != 0 && currentAssetState == Config.STATE_NOT_USE) {
                        ArrayList<Hashtable<String, String>> listData = GetCity();
                        showAvatarPop(listData);
                    } else if (currentAssetState == Config.STATE_USING) {
                        Intent i = new Intent(MainActivity.this, FinishActivity.class);
                        i.putExtra("assertName", assertName);
                        i.putExtra("operaName", currentOperation);
                        startActivity(i);
                    } else {
                        showToast("请先绑定科室");
                    }
                } else
                    Toast.makeText(MainActivity.this, "将手机贴近标签", Toast.LENGTH_SHORT).show();
            }
        });
        card1.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Intent i = new Intent();
                i.setClass(MainActivity.this, WriteTagActivity.class);
                if (currentMap != null) {
                    i.putExtra("tagData", (Serializable) currentMap);
                }
                startActivity(i);
            }
        });
        card2.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Intent i = new Intent(MainActivity.this, HistoryActivity.class);
                i.putExtra("assetId", currentAssetId);
                startActivity(i);
            }
        });

        card3.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                cancelKel = 0;
                isKeshi = true;
                currentKeshiId = BmobUser.getCurrentUser(MainActivity.this, User.class).getKeshiId();
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                setKeshiDialog = builder.setSingleChoiceItems(keshiIteams, keshiItemOption, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        currentKeshiName = keshiIteams[i];
                        currentKeshi = i;
                        mCardText.setText("绑定科室-" + currentKeshiName);
                        keshiItemOption = i;
                    }
                })
                        .setTitle("选择科室,扫描标签")
                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                isKeshi = false;
                            }
                        })
                        .show();

            }
        });
        card4.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                cancelKel = 1;
                isKeshi = true;
                currentKeshiId = 0;
                showKeshiDia("解除科室", "扫描tag以解除科室");
            }
        });
    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        isKeshi = false;
        if (nfcAdapter != null)
            nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters, mTechLists);
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
            Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
            String result = processIntent(getIntent());
            if (result != null)
                readTag(result);
            if (isKeshi) {
                isKeshi = false;
                setTagKeshi(currentAssetId, currentKeshiId, tag);

                if (cancelKel == 1) {
                    writekeshiDialog.dismiss();
                } else {
                    setKeshiDialog.dismiss();
                }

            }
        }
    }

    @SuppressLint("NewApi")
    @Override
    // nfc的响应事件
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            String result = processIntent(intent);
            if (isStartService) {
                isStartService = false;
                startService(currentOperation, tag);
                startOperaDialog.dismiss();
                return;
            }
            if (isKeshi) {
                isKeshi = false;
                setTagKeshi(currentAssetId, currentKeshiId, tag);

                if (cancelKel == 1) {
                    writekeshiDialog.dismiss();
                } else {
                    if (setKeshiDialog != null)
                        setKeshiDialog.dismiss();
                }

            }
            if (result != null)
                readTag(result);

        }
    }

    /**
     * 获取tab标签中的内容
     */
    @SuppressLint("NewApi")
    private String processIntent(Intent intent) {
        try {
            Parcelable[] rawmsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage msg = (NdefMessage) rawmsgs[0];
            NdefRecord[] records = msg.getRecords();
            String resultStr = new String(records[0].getPayload());
            return resultStr;
        } catch (Exception e) {
//            showToast("读取失败");
        }
        return null;
    }

    /**
     * 从Tag中读取数据
     */
    private void readTag(String str) {
        Gson gson = new Gson();
        try {
            Map<String, Object> map = gson.fromJson(str, new TypeToken<Map<String, Object>>() {
            }.getType());
            currentMap = new HashMap<String, Object>();
            currentMap = map;
            assertName = (String) map.get(Config.Tag_name);
            int tag_keshi = (int) ((double) map.get(Config.Tag_curKeshi));
            int assetType = (int) ((double) map.get(Config.Tag_type));
            //仅仅在标签中的科室名称为未绑定且与要绑定的科室不同，要绑定科室不为未绑定时才绑定
            if ((tag_keshi == Config.Keshi_NULL) || (!(tag_keshi == currentKeshi)) || !(currentKeshiName.equals("无科室"))) {
                isKeshi = true;
            } else {
                isKeshi = false;
            }
            currentAssetId = (String) map.get(Config.Tag_id);
            currentAssetState = (int) ((double) map.get(Config.Tag_state));
            currentOperation = (String) map.get(Config.Tag_curOperation);
            if (currentAssetState == Config.STATE_NOT_USE) {
                mState.setText("资产状态：待用");
                mServiceText.setText("开 始\n服 务");
            } else {
                mState.setText("资产状态：正在使用中");
                mServiceText.setText("正 在\n使 用");
            }
            String keshiName = "暂无所在科室";
            String assetTypeName = "";
            switch (tag_keshi) {
                case Config.Keshi_Heart:
                    keshiName = "心脏科";
                    break;
                case Config.Keshi_Mouth:
                    keshiName = "口腔科";
                    break;
                case Config.Keshi_Nerve:
                    keshiName = "神经科";
                    break;

            }
            switch (assetType) {
                case Config.AssetType_BREATH:
                    assetTypeName = "呼吸机";
                    break;
                case Config.AssetType_CUSA:
                    assetTypeName = "超声刀";
                    break;
            }
            mKeShi.setText("所在科室：" + keshiName);
            mName.setText("资产名称：" + map.get(Config.Tag_name));
            mType.setText("资产类型：" + assetTypeName);

            mBirth.setText("生产日期：" + map.get(Config.Tag_birth));
            mDate.setText("资产到期：" + map.get(Config.Tag_date));
            mManu.setText("资产厂商：" + map.get(Config.Tag_manu));
            mOperaTion.setText("最近手术类型：" + map.get(Config.Tag_curOperation));

            isStart = true;
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "Tag格式不正确", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressWarnings("deprecation")
    private void showAvatarPop(final ArrayList<Hashtable<String, String>> listFilePath) {
        if (listFilePath == null || listFilePath.size() == 0) {
            return;
        }
        View view = LayoutInflater.from(this).inflate(R.layout.pop_showavator, null);
        layout_all = (LinearLayout) findViewById(R.id.layout_alllayout);

        final ListView operationType = (ListView) view.findViewById(R.id.lvSudokuItems);
        final SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, listFilePath, R.layout.filelist,
                new String[]{FILENAME}, new int[]{R.id.tvSudokuItem});
        operationType.setAdapter(adapter);

        operationType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressWarnings("unchecked")
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                isStartService = true;
                currentOperation = ((Hashtable<String, String>) adapter.getItem(position)).get(FILENAME);
                startOperaDialog = new DialogTips(MainActivity.this, currentKeshiName, "再次扫描标签以开始服务", "取消", false, true);
                startOperaDialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        isStartService = false;

                    }
                });
                startOperaDialog.show();
            }
        });

        avatorPop = new PopupWindow(view, 600, 600);
        avatorPop.setTouchInterceptor(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    avatorPop.dismiss();
                    return true;
                }
                return false;
            }
        });

        avatorPop.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        avatorPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        avatorPop.setTouchable(true);
        avatorPop.setFocusable(true);
        avatorPop.setOutsideTouchable(true);
        avatorPop.setBackgroundDrawable(new BitmapDrawable());
        // 动画效果 从底部弹起
        avatorPop.setAnimationStyle(R.style.Animations_GrowFromBottom);
        avatorPop.showAtLocation(layout_all, Gravity.BOTTOM, 0, 0);
    }

    private ArrayList<Hashtable<String, String>> GetCity() {
        ArrayList<Hashtable<String, String>> listData = new ArrayList<Hashtable<String, String>>();
        Hashtable<String, String> hmItem = new Hashtable<String, String>();
        hmItem.put(FILENAME, "腔镜手术");
        listData.add(hmItem);
        hmItem = new Hashtable<String, String>();
        hmItem.put(FILENAME, "开放胃食管手术");
        listData.add(hmItem);
        hmItem = new Hashtable<String, String>();
        hmItem.put(FILENAME, "微创手术");
        listData.add(hmItem);
        hmItem = new Hashtable<String, String>();
        hmItem.put(FILENAME, "皱皮拉除");
        listData.add(hmItem);
        hmItem = new Hashtable<String, String>();
        hmItem.put(FILENAME, "开放直肠癌手术");
        listData.add(hmItem);
        hmItem = new Hashtable<String, String>();
        hmItem.put(FILENAME, "皮肤癌手术");
        listData.add(hmItem);
        hmItem = new Hashtable<String, String>();
        hmItem.put(FILENAME, "其他手术");
        listData.add(hmItem);
        return listData;
    }

    /**
     * 显示绑定科室对话框
     */
    private void showKeshiDia(String titleStr, String msg) {
        writekeshiDialog = new DialogTips(this, titleStr, msg, "取消", false, true) {
            @Override
            protected boolean OnClickPositiveButton() {
                isKeshi = false;
                return super.OnClickPositiveButton();

            }
        };
        writekeshiDialog.show();
    }

    private void showToast(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    private String getKeshi(String tagId) {
        BmobQuery<Asset> query = new BmobQuery<Asset>();
        query.addWhereEqualTo("cusId", tagId);
        query.findObjects(this, new FindListener<Asset>() {

            @Override
            public void onSuccess(List<Asset> arg0) {
                // TODO Auto-generated method stub
                if (arg0.size() == 0) {
                    currentKeshiName = "网络不畅";
                    return;
                }
                Asset asset = arg0.get(0);
                currentKeshiId = asset.getKeShiId();
                currentKeshiName = getKeshiName(asset.getKeShiId());
            }

            @Override
            public void onError(int arg0, String arg1) {
                // TODO Auto-generated method stub

            }
        });
        return currentKeshiName;
    }

    private String getKeshiName(int keshiId) {

        BmobQuery<KeShi> query = new BmobQuery<KeShi>();
        query.addWhereEqualTo("keshiId", keshiId);
        query.findObjects(this, new FindListener<KeShi>() {
            @Override
            public void onSuccess(List<KeShi> list) {
                if (list != null) {
                    currentKeshiName = list.get(0).getKeshiName();
                    mKeShi.setText("所在科室: " + currentKeshiName);

                } else {
                    currentKeshiName = "暂无\"所在科室: \"科室信息";
                    mKeShi.setText("所在科室: " + "科室信息获取失败");

                }

            }

            @Override
            public void onError(int i, String s) {
                showToast("网络请求失败,请确认网络已连接");
            }
        });

        return currentKeshiName;
    }

    /**
     * 在后台设置标签的ａｓｓｅｔ的科室所在
     *
     * @param tagId 标签的ｉｄ keshiId 科室的ｉｄ；
     */
    private boolean setTagKeshi(String tagId, final int keshiId, Tag tag) {
//        BmobQuery<Asset> query = new BmobQuery<Asset>();
//        query.addWhereEqualTo("cusId", tagId);
//        query.findObjects(this, new FindListener<Asset>() {
//
//            @Override
//            public void onSuccess(List<Asset> arg0) {
//                // TODO Auto-generated method stub
//                Asset currentAsset = arg0.get(0);
//                currentAsset.setKeShiId(keshiId);
//                currentAsset.update(MainActivity.this, new UpdateListener() {
//
//                    @Override
//                    public void onSuccess() {
//                        // TODO Auto-generated method stub
//                        if (cancelKel == 0) {
//                            showToast("绑定科室成功");
//                        } else {
//                            showToast("解除科室成功");
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(int arg0, String arg1) {
//                        // TODO Auto-generated method stub
//                        showToast("绑定失败" + arg1);
//                    }
//                });
//            }
//
//            @Override
//            public void onError(int arg0, String arg1) {
//                // TODO Auto-generated method stub
//
//            }
//        });
        if (cancelKel == 1) currentMap.put(Config.Tag_curKeshi, Config.Keshi_NULL);
        else currentMap.put(Config.Tag_curKeshi, currentKeshi);
        boolean isSucceed = BaseApplication.getInstance().writeTag(currentMap, tag);
        int keshiID = (int) (currentMap.get(Config.Tag_curKeshi));
        if (isSucceed) {
            mKeShi.setText("所在科室: " + Config.getKeshiById(keshiID));
        }
        isKeshi = false;
        return isSucceed;

    }

    /**
     * 更新资产状态
     */
    private void updateAssetState(String assetId) {
        BmobQuery<Asset> query = new BmobQuery<Asset>();
        query.addWhereEqualTo("cusId", assetId);

        query.findObjects(this, new FindListener<Asset>() {

            @Override
            public void onSuccess(List<Asset> arg0) {
                // TODO Auto-generated method stub
                Asset curAsset = arg0.get(0);
                curAsset.setStatus(currentAssetState);
                curAsset.update(MainActivity.this, new UpdateListener() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onFailure(int i, String s) {
                    }
                });
            }

            @Override
            public void onError(int arg0, String arg1) {
                // TODO Auto-generated method stub

            }
        });
    }

    private String getUserKeShiName() {
        SharedPreferences setPre = this.getSharedPreferences("user", 0);
        return setPre.getString("keshiName", "该用户暂无所属科室");
    }

    /**
     * 点击开始服务，选择手术后，扫描成功，运行该函数
     *
     * @param strPreview 被选中的操作类型
     */
    private void startService(String strPreview, Tag tag) {
        mRecord = new Record();
        mRecord.setAssertId(currentAssetId);
        mRecord.setCustId(User.getCurrentUser(MainActivity.this).getObjectId());// 保存操作记录同步到云端
        mRecord.setOperationType(strPreview);
        mRecord.setKeshiName(currentKeshiName);
        mRecord.save(MainActivity.this, new SaveListener() {
            @Override
            public void onSuccess() {
                showToast("上传记录成功");
                currentAssetState = Config.STATE_USING;
                updateAssetState(currentAssetId);

            }

            @Override
            public void onFailure(int arg0, String arg1) {
                // TODO Auto-generated method stub
                showToast("无网络，将记录本地存储");
                LocalData localData = new LocalData();
                localData.saveData(mRecord);
            }
        });
        currentMap.put(Config.Tag_state, Config.STATE_USING);
        currentMap.put(Config.Tag_curOperation, currentOperation);
        if (BaseApplication.getInstance().writeTag(currentMap, tag)) {
            Intent intent = new Intent(MainActivity.this, FinishActivity.class);
            intent.putExtra("record", mRecord.getObjectId());
            intent.putExtra("operaName", currentOperation);
            intent.putExtra("assertName", assertName);
            startActivity(intent);
        }
    }

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onDestroy() {
        this.unregisterReceiver(netChangeBroad);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //处理扫描结果
        if (resultCode == RESULT_OK&&requestCode == Reqeusted_QR){
            showToast(data.getExtras().getString("result"));
        }
    }
}